<template>
  <view class="forget_container">
    <!-- <view class="logo-area">
      <image class="logo" src="/static/logo.png" mode="aspectFit"></image>
      <text class="title">找回密码</text>
    </view> -->
    
    <view class="form-card">
      <!-- 邮箱输入 -->
      <view class="input-group">
        <text class="label">邮箱地址</text>
        <view class="input-container" :class="{ 'input-error': emailError }">
          <input
            class="input"
            type="text"
            v-model="email"
            placeholder="请输入您的邮箱"
            @blur="validateEmail"
          />
        </view>
        <text v-if="emailError" class="error-message">{{ emailError }}</text>
      </view>
      
      <!-- 验证码 -->
      <view class="input-group">
        <text class="label">验证码</text>
        <view class="verification-container">
          <view class="input-container code-input" :class="{ 'input-error': codeError }">
            <input
              class="input"
              type="number"
              maxlength="6"
              v-model="verificationCode"
              placeholder="请输入6位验证码"
              @blur="validateCode"
            />
          </view>
          <button
            class="send-code-btn"
            :disabled="isSending || !isEmailValid"
            :class="{ 'btn-disabled': isSending || !isEmailValid }"
            @click="sendVerificationCode"
          >
            {{ sendBtnText }}
          </button>
        </view>
        <text v-if="codeError" class="error-message">{{ codeError }}</text>
      </view>
      
      <!-- 新密码 -->
      <view class="input-group">
        <text class="label">新密码</text>
        <view class="input-container" :class="{ 'input-error': passwordError }">
          <input
            class="input"
            :type="showPassword ? 'text' : 'password'"
            v-model="password"
            placeholder="请输入不少于6位的新密码"
            @blur="validatePassword"
          />
          <view class="eye-icon" @click="togglePasswordVisibility">
            <uni-icons
              v-if="showPassword"
              custom-prefix="iconfont"
              type="icon-yanjing_xianshi_o"
              size="30"
            ></uni-icons>
            <uni-icons
              v-else
              custom-prefix="iconfont"
              type="icon-yanjing_yincang_o"
              size="30"
            ></uni-icons>
          </view>
        </view>
        <text v-if="passwordError" class="error-message">{{ passwordError }}</text>
      </view>
      
      <!-- 确认密码 -->
      <view class="input-group">
        <text class="label">确认密码</text>
        <view class="input-container" :class="{ 'input-error': confirmPasswordError }">
          <input
            class="input"
            :type="showConfirmPassword ? 'text' : 'password'"
            v-model="confirmPassword"
            placeholder="请再次输入新密码"
            @blur="validateConfirmPassword"
          />
          <view class="eye-icon" @click="toggleConfirmPasswordVisibility">
            <uni-icons
              v-if="showConfirmPassword"
              custom-prefix="iconfont"
              type="icon-yanjing_xianshi_o"
              size="30"
            ></uni-icons>
            <uni-icons
              v-else
              custom-prefix="iconfont"
              type="icon-yanjing_yincang_o"
              size="30"
            ></uni-icons>
          </view>
        </view>
        <text v-if="confirmPasswordError" class="error-message">{{ confirmPasswordError }}</text>
      </view>
      
      <!-- 提交按钮 -->
      <button
        class="submit-btn"
        :disabled="!isFormValid"
        :class="{ 'btn-disabled': !isFormValid }"
        @click="resetPassword"
      >
        重置密码
      </button>
      
      <!-- 返回登录 -->
      <view class="back-to-login" @click="goToLogin">
        <text>返回登录页面</text>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';

// 响应式状态
const email = ref('');
const verificationCode = ref('');
const password = ref('');
const confirmPassword = ref('');
const showPassword = ref(false);
const showConfirmPassword = ref(false);

// 错误信息
const emailError = ref('');
const codeError = ref('');
const passwordError = ref('');
const confirmPasswordError = ref('');

// 发送验证码相关
const isSending = ref(false);
const countdown = ref(0);
const sendBtnText = computed(() => {
  if (isSending.value) {
    return `${countdown.value}秒后重试`;
  }
  return '发送验证码';
});

// 表单验证状态
const isEmailValid = computed(() => {
  return email.value && !emailError.value;
});

const isFormValid = computed(() => {
  return (
    isEmailValid.value && 
    verificationCode.value.length === 6 && 
    password.value.length >= 6 && 
    password.value === confirmPassword.value &&
    !emailError.value && 
    !codeError.value && 
    !passwordError.value && 
    !confirmPasswordError.value
  );
});

// 邮箱验证
const validateEmail = () => {
  const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
  if (!email.value) {
    emailError.value = '请输入邮箱地址';
  } else if (!emailRegex.test(email.value)) {
    emailError.value = '请输入有效的邮箱地址';
  } else {
    emailError.value = '';
  }
};

// 验证码验证
const validateCode = () => {
  if (!verificationCode.value) {
    codeError.value = '请输入验证码';
  } else if (verificationCode.value.length !== 6) {
    codeError.value = '验证码必须为6位数字';
  } else {
    codeError.value = '';
  }
};

// 密码验证
const validatePassword = () => {
  if (!password.value) {
    passwordError.value = '请输入新密码';
  } else if (password.value.length < 6) {
    passwordError.value = '密码不能少于6位';
  } else {
    passwordError.value = '';
  }
};

// 确认密码验证
const validateConfirmPassword = () => {
  if (!confirmPassword.value) {
    confirmPasswordError.value = '请确认新密码';
  } else if (confirmPassword.value !== password.value) {
    confirmPasswordError.value = '两次输入的密码不一致';
  } else {
    confirmPasswordError.value = '';
  }
};

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;
};

const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value;
};

// 发送验证码
const sendVerificationCode = async () => {
  if (!isEmailValid.value || isSending.value) {
    return;
  }
  
  try {
    isSending.value = true;
    uni.showLoading({ title: '发送中...' });
    
    // 调用发送邮件接口
    const result = await sendEmalil(email.value, 'reset');
    
    // 如果发送成功，开始倒计时
    if (result === 1) {
      startCountdown();
    }
    
  } catch (error) {
    uni.hideLoading();
    uni.$showT('发送失败，请稍后重试');
    console.error('发送验证码失败:', error);
    isSending.value = false;
  }
};

// 倒计时功能
const startCountdown = () => {
  countdown.value = 60;
  const timer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(timer);
      isSending.value = false;
    }
  }, 1000);
};

// 重置密码
const resetPassword = async () => {
  // 先验证表单
  validateEmail();
  validateCode();
  validatePassword();
  validateConfirmPassword();
  
  if (!isFormValid.value) {
    uni.$showT('请完善表单信息');
    return;
  }
  
  try {
    uni.showLoading({ title: '提交中...' });
    
    // 调用重置密码接口
    const res = await uni.$http.post("/user/findPassword", {
      email: email.value,
      code: verificationCode.value,
      newPassword: password.value
    });
    
    uni.hideLoading();
    
    if (res.data.code === 1) {
      uni.$showT('密码重置成功!');
      // 延迟跳转到登录页
      setTimeout(() => {
        goToLogin();
      }, 1500);
    } else {
      uni.$showT(res.data.msg || '密码重置失败，请重试');
    }
    
  } catch (error) {
    uni.hideLoading();
    uni.$showT('网络错误，请稍后重试');
    console.error('重置密码失败:', error);
  }
};

// 执行邮件发送函数
async function sendEmalil(targetEmail, type) {
  let res = await uni.$http.post("/common/sendEmailCode", {email: targetEmail});
  
  if(res.data.code == 0) {
    uni.$showT(res.data.msg);
    uni.hideLoading();
    return 1;
  }
  
  // 发送成功，隐藏Loading，显示成功提示
  uni.hideLoading();
  uni.$showT("邮件发送成功!");
  return 1;
}

// 跳转到登录页
const goToLogin = () => {
  uni.redirectTo({
  	url: "/pages/auth/auth"
  })
};
</script>

<style>
.forget_container {
  padding: 40rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  /* min-height: 100vh; */
  background-color: #f8f8f8;
  box-sizing: border-box;
}

.logo-area {
  margin-bottom: 60rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.logo {
  width: 160rpx;
  height: 160rpx;
  margin-bottom: 20rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.form-card {	
	box-sizing: border-box;
	width: 100%;
	background-color: #fff;
	border-radius: 20rpx;
	padding: 40rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.input-group {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 12rpx;
}

.input-container {
  display: flex;
  align-items: center;
  border: 1rpx solid #e0e0e0;
  border-radius: 8rpx;
  height: 80rpx;
  padding: 0 24rpx;
  background-color: #f9f9f9;
  position: relative;
}

.input {
  flex: 1;
  height: 80rpx;
  font-size: 28rpx;
  color: #333;
}

.eye-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 10rpx;
}

.verification-container {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.code-input {
  flex: 1;
}

.send-code-btn {
  width: 220rpx;
  height: 80rpx;
  background-color: #007aff;
  color: white;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8rpx;
  padding: 0;
}

.btn-disabled {
  background-color: #cccccc !important;
  color: #ffffff !important;
}

.input-error {
  border-color: #ff4d4f;
}

.error-message {
  color: #ff4d4f;
  font-size: 24rpx;
  margin-top: 8rpx;
}

.submit-btn {
  width: 100%;
  height: 90rpx;
  background-color: #007aff;
  color: white;
  font-size: 32rpx;
  font-weight: 500;
  border-radius: 45rpx;
  margin-top: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 16rpx rgba(0, 122, 255, 0.3);
}

.back-to-login {
  margin-top: 40rpx;
  display: flex;
  justify-content: center;
}

.back-to-login text {
  color: #007aff;
  font-size: 28rpx;
}
</style>